package com.hnkywl.sts.service.cwgl.kmys;

import com.google.gson.Gson;
import com.hnkywl.sts.dao.cwgl.KhzhsfmxDao;
import com.hnkywl.sts.dao.cwgl.KmdmDao;
import com.hnkywl.sts.dao.cwgl.pjdr.YhsxdrDao;
import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.dao.zjgl.YhsxmxDao;
import com.hnkywl.sts.entity.cwgl.Khzhsfmx;
import com.hnkywl.sts.entity.cwgl.Kmdm;
import com.hnkywl.sts.entity.cwgl.VoucherItemData;
import com.hnkywl.sts.entity.sfgl.Sfk;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.entity.zjgl.Xyz;
import com.hnkywl.sts.entity.zjgl.Yhsx;
import com.hnkywl.sts.entity.zjgl.Yhsxmx;
import com.hnkywl.sts.service.cwgl.KhzhsfmxService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.service.zjgl.YhsxService;
import com.hnkywl.sts.service.zjgl.YhsxmxService;
import com.hnkywl.sts.util.BaseUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: lenovo
 * Date: 13-6-3
 * Time: 下午3:13
 * To change this template use File | Settings | File Templates.
 */
@Service
public class YhsxdrService {
    private YhsxdrDao yhsxdrDao;

    private KhzhsfmxDao khzhsfmxDao;

    private KhzhsfmxService khzhsfmxService;

    private GsjgDao gsjgDao;

    private YhsxService yhsxService;

    private YhsxmxDao yhsxmxDao;

   private YhsxmxService yhsxmxService;

    private KmdmDao kmdmDao;

    @Transactional
    public String findAllYhsxdr(Long gsId,String gsMc,Date jkrqStart,Date jkrqEnd,Integer yhsxdrZt,int page,int  rows) {
        Long nbgsIds = null;
        if(gsId !=null && gsMc!=null && gsMc.equals(gsjgDao.get(gsId).getJc())){
            nbgsIds = gsId;
        }
        Page<Yhsxmx> yhsxPage = this.yhsxdrDao.findYhsxdrList(nbgsIds, gsMc, jkrqStart, jkrqEnd, yhsxdrZt,page, rows);
        List<Yhsxmx> yhsxList = yhsxPage.getResult() == null ? new ArrayList<Yhsxmx>() : yhsxPage.getResult();
        if(yhsxList.size()>0){
            yhsxList = getCzztByPj(yhsxList);
        }
        String yhsxJson = BaseUtils.fetchCollectionToJson(yhsxList, "id","yhsx.nbgs.jc", "yhsx.jkrq","yhsx.khh.qc",
                "hkje", "hxje", "hkrq", "czzt", "zffs.z","bz","yhsxsflx","yhsx.jkje","voucherNum");
        return "{\"total\":" + yhsxPage.getTotalCount() + ",\"rows\":[" + yhsxJson + "]}";
    }

    public List<Yhsxmx> getCzztByPj(List<Yhsxmx> yhsxmxList){
        for(Yhsxmx p:yhsxmxList){
            String czzt = "";
            if(p.getInsertFlag()==1 && p.getDeleteFlag()==1){
                czzt = "wdr";
            }else if(p.getInsertFlag()==1 && p.getDeleteFlag()==3){
                czzt = "sccg";
            }else if(p.getInsertFlag()==3 && p.getDeleteFlag()==1){
                czzt = "drcg";
            }else if(p.getInsertFlag()==2 && p.getDeleteFlag()==1 ||p.getInsertFlag()==2 && p.getDeleteFlag()==3 ){
                czzt = "drsb";
            }else if(p.getInsertFlag()==3 && p.getDeleteFlag()==2){
                czzt = "scsb";
            }else{
                czzt = "null";
            }
            p.setCzzt(czzt);
        }
        return yhsxmxList;
    }

    @Transactional
    public Map getVoucherMaster(Long id, Integer attachment, String uuid, String year, String mouth, Yg yg) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate =simple.format(new Date());
        Map<String, Object> voucherMaster = new HashMap<String, Object>();
        voucherMaster.put("id", uuid);
        voucherMaster.put("vchrtypecode", this.yhsxmxDao.get(id).getYhsx().getKhh().getDrzh());//凭证类别
        voucherMaster.put("acctyear", year != null ? year : "");//会计年度
        voucherMaster.put("acctperiod", mouth != null ? mouth : "");//会计期间
        voucherMaster.put("createdate", systemDate);//凭证日期
        voucherMaster.put("unitcode", this.yhsxmxDao.get(id).getYhsx().getNbgs().getJiuqiUnitCode());//组织机构代码
        voucherMaster.put("acctbookcode", "01");//账薄标识
        voucherMaster.put("createuser", yg.getDlm());//制单人
        voucherMaster.put("attachment", attachment);//附件张数
        voucherMaster.put("memo", "");//备注
        voucherMaster.put("companyId",   this.yhsxmxDao.get(id).getYhsx().getNbgs().getId());//公司ID
        return voucherMaster;
    }

    @Transactional
    public String findyhsxdrFl(Long id) {
        Yhsxmx yhsxmx = this.yhsxmxDao.get(id);
        List<VoucherItemData> list = this.yhsxdrDao.getVoucher(yhsxmx);
        List<Map> txcdJson = new ArrayList<Map>();
        for (int i =0;i<list.size() ;  i++){
            VoucherItemData voucherItemData = list.get(i);
            Map<String, Object> voucherItem = new HashMap<String, Object>();
            voucherItem.put("zy",voucherItemData.getZy());
            voucherItem.put("km",voucherItemData.getKmmc());
            voucherItem.put("df",voucherItemData.getDf()==null?0:voucherItemData.getDf());
            voucherItem.put("jf",voucherItemData.getJf()==null?0:voucherItemData.getJf());
            txcdJson.add(voucherItem);
        }
        return new Gson().toJson(txcdJson);
    }

    @Transactional
    public Map getRevokeInfo(Long id) {
        Map<String, Object> revokeInfo = new HashMap<String, Object>();
        Yhsxmx result = yhsxdrDao.get(id);
        if (result == null) {
            throw new RuntimeException("没该公司的对照信息!");
        }
        revokeInfo.put("id", result.getUuid());//凭证ID
        revokeInfo.put("vchrid", result.getVoucherId());//凭证ID
        revokeInfo.put("unitcode", result.getYhsx().getNbgs().getJiuqiUnitCode());//单位代码
        revokeInfo.put("acctyear", result.getAcctyear());//会计年度
        return revokeInfo;
    }

    @Transactional
    public Map getVoucher(Long id, String uuid, List<VoucherItemData> voucherItemDataList) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String systemDate =simple.format(new Date());
        Yhsxmx yhsxmx = this.yhsxmxDao.get(id);
        List<VoucherItemData> list = this.yhsxdrDao.getVoucher(yhsxmx);
        DecimalFormat df = new DecimalFormat("#.##");
        Map<String, Object> result = new HashMap<String, Object>();
        //凭证分录信息
        List<Map> items = new ArrayList<Map>();
        int order = 1;
        for (VoucherItemData item : list) {
            Map<String, Object> voucherItem = new HashMap<String, Object>();
            voucherItem.put("id", order);//唯一标识
            voucherItem.put("vchrid", uuid);//凭证主表ID
            voucherItem.put("itemorder", order);//分录编号
            voucherItem.put("subjectcode", item.getKmdm() != null && item.getKmdm() != null ? item.getKmdm() : "");//科目代码
            voucherItem.put("subjectname", item.getKmdm() != null && item.getKmmc() != null ? item.getKmmc() : "");//科目名称
            voucherItem.put("debit", item.getJf() != null ? df.format(item.getJf()) : 0.00);//借方金额
            voucherItem.put("credit", item.getDf() != null ? df.format(item.getDf()) : 0.00);//贷方金额
            voucherItem.put("qty", item.getQty() != null ? item.getQty() : 0);//数量
            voucherItem.put("price", 0);//单价
            voucherItem.put("currencycode", "CNY");//货币代码
            voucherItem.put("exchrate", 1.000000);//汇率
            voucherItem.put("orgnd", item.getJf() != null ? df.format(item.getJf()) : 0.00);//借方原币
            voucherItem.put("orgnc", item.getDf() != null ? df.format(item.getDf()) : 0.00);//贷方原币
            voucherItem.put("settlementcode", "");//结算方式代码
            voucherItem.put("settlementno", "");//结算号
            voucherItem.put("bizdate", simple.format(new Date()));//业务日期
            voucherItem.put("digest", item.getZy() != null ? item.getZy() : "");//摘要
            voucherItem.put("bizno", "");//业务号
            voucherItem.put("suppliername", item.getSupplierName() != null ? item.getSupplierName() : "");//供应商名称
            voucherItem.put("suppliercode", item.getSupplierCode() != null ? item.getSupplierCode() : "");//供应商代码
            voucherItem.put("departmentname", item.getDeptName() != null ? item.getDeptName() : "");//部门名称
            voucherItem.put("departmentcode", item.getDeptCode() != null ? item.getDeptCode() : "");//部门代码
            voucherItem.put("customername", item.getCustomerName() != null ? item.getCustomerName() : "");//客户名称
            voucherItem.put("customercode", item.getCustomerCode() != null ? item.getCustomerCode() : "");//客户代码
            voucherItem.put("staffname", item.getUserName() != null ? item.getUserName() : "");//职员名称
            voucherItem.put("staffcode", item.getUserCode() != null ? item.getUserCode() : "");//职员代码
            items.add(voucherItem);
            order++;
        }
        result.put("items", items);
        return result;
    }

    @Transactional
    public Map getU8VoucherItems(Long id, String uuid, List<VoucherItemData> voucherItemDataList) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String systemDate =simple.format(new Date());
        Yhsxmx yhsxmx = this.yhsxmxDao.get(id);
        List<VoucherItemData> list = this.yhsxdrDao.getVoucher(yhsxmx);
        DecimalFormat df = new DecimalFormat("#.##");
        Map<String, Object> result = new HashMap<String, Object>();
        //凭证分录信息
        List<Map> items = new ArrayList<Map>();
        int order = 1;
        for (VoucherItemData item : list) {
            Map<String, Object> voucherItem = new HashMap<String, Object>();
            voucherItem.put("entry_id", order);//分录编号
            voucherItem.put("account_code", item.getKmdm() != null ? item.getKmdm() : "");//科目代码
            voucherItem.put("natural_debit_currency", item.getJf() != null ? df.format(item.getJf()) : 0.00);//借方金额
            voucherItem.put("natural_credit_currency",item.getDf() != null ? df.format(item.getDf()) : 0.00);//贷方金额
            voucherItem.put("unit_price", "0");//单价,在科目有数量核算时，填写此项
            voucherItem.put("debit_quantity", "0");//借方数量,在科目有数量核算时，填写此项
            voucherItem.put("credit_quantity", "0");//贷方数量,在科目有数量核算时，填写此项
            voucherItem.put("currency", "CNY");//货币代码
            voucherItem.put("exchange_rate2", "1.000000");//汇率
            voucherItem.put("settlement", "");//结算方式,在科目是银行或往来时，可以填写此项
            voucherItem.put("document_id", "");//票据号，在科目是银行或往来时，可以填写此项
            voucherItem.put("document_date",systemDate);//票据日期，在科目是银行或往来时，可以填写此项
            voucherItem.put("abstract",item.getZy() != null ? item.getZy() : "");//摘要
            Map<String, String> fzhsMap = new HashMap<String, String>();
            Map<String, Map> xjllxmMap = new HashMap<String, Map>();
            fzhsMap =  this.findFzhsByMap(yhsxmx,item,fzhsMap,xjllxmMap);
            voucherItem.put("auxiliary_accounting", fzhsMap);
            voucherItem.put("cash_flow", xjllxmMap);
            items.add(voucherItem);
            order++;
        }
        result.put("items", items);
        return result;
    }


    private Map<String,String > findFzhsByMap(Yhsxmx yhsxmx, VoucherItemData voucherItemData,Map<String, String> fzhsMap, Map<String, Map> xjllxmMap){
        DecimalFormat df = new DecimalFormat("#.##");
        //1.更具公司还有代码查询科目代码
        Kmdm kmdm = kmdmDao.findKmdmDetailByGs(yhsxmx.getYhsx().getNbgs().getId(),voucherItemData.getKmdm());
        if(kmdm==null){
            kmdm = kmdmDao.findKmdmDetailByGs(YgService.getCurrentYgZgGsId(),voucherItemData.getKmdm());
        }
        //2.现金流量项目
        if(kmdm!=null&& kmdm.getXjllsx() !=null && !"".equals(kmdm.getXjllsx()) &&  kmdm.getXjllsx().equals("Y")){
            fzhsMap.put("item_id", "01");
            Map value = new HashMap<String, Double>();
            Double d = voucherItemData.getJf() != null ? voucherItemData.getJf() : 0.00 ;
            Double c = voucherItemData.getDf() != null ? voucherItemData.getDf() : 0.00;
            value.put("debit", d);
            value.put("credit", c);
            value.put("md", Math.abs(d - c));
            value.put("ccode", voucherItemData.getKmdm());
            xjllxmMap.put("01", value);
        }//3.其他项目
        else  if(kmdm !=null && kmdm.getTyfzhsmc()!=null && kmdm.getTyfzhsys() != null ){
            fzhsMap.put("item_id",kmdm.getTyfzhsys().getCode() );
        }
        else{
            if(voucherItemData.getCustomerCode() !=null ){
                fzhsMap.put("cust_id",voucherItemData.getCustomerCode());
            }
            if(voucherItemData.getSupplierCode() !=null ){
                fzhsMap.put("supplier_id",voucherItemData.getSupplierCode());
                fzhsMap.put("operator","-");
            }
        }
        return fzhsMap;
    }

    @Transactional
    public String revokeNote(Long yhsxId) {
        String error = null;
        Yhsxmx yhsxmx = this.yhsxmxDao.get(yhsxId);
        try {
          yhsxmx.setDeleted(1);
          yhsxmx.setLastUpdated(new Date());
          this.yhsxmxService.saveYhsxmx(yhsxmx);
          Double ljhk = Double.parseDouble(yhsxmx.getYhsx().getLjhk().toString())-Double.parseDouble(yhsxmx.getHkje().toString());
          if(yhsxmx.getYhsx().getYhsxmxList().size()==2){
              yhsxmx.getYhsx().setZt(1); //确认
          }else if(ljhk < Double.parseDouble(yhsxmx.getYhsx().getJkje().toString()) && ljhk != 0d){
              yhsxmx.getYhsx().setZt(2); //还款中
          }
          yhsxmx.getYhsx().setLjhk(ljhk);
          yhsxService.saveOldYhsx(yhsxmx.getYhsx());
          List<Khzhsfmx> khzhsfmxList = this.khzhsfmxDao.findKhzhsfmxByYhsxmx(yhsxmx.getId());
          if(khzhsfmxList.size()>0){
              for(Khzhsfmx khzhsfmx :khzhsfmxList){
                  khzhsfmx.setLastUpdated(new Date());
                  khzhsfmx.setDeleted(1);
                  khzhsfmxDao.save(khzhsfmx);
              }
          }
        } catch (Exception e) {
            error = e.getMessage();
        }
        return error;
    }



    @Autowired
    public void setYhsxdrDao(YhsxdrDao yhsxdrDao) {
        this.yhsxdrDao = yhsxdrDao;
    }
    @Autowired
    public void setKhzhsfmxDao(KhzhsfmxDao khzhsfmxDao) {
        this.khzhsfmxDao = khzhsfmxDao;
    }
    @Autowired
    public void setKhzhsfmxService(KhzhsfmxService khzhsfmxService) {
        this.khzhsfmxService = khzhsfmxService;
    }
    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }
    @Autowired
    public void setYhsxmxDao(YhsxmxDao yhsxmxDao) {
        this.yhsxmxDao = yhsxmxDao;
    }
    @Autowired
    public void setYhsxmxService(YhsxmxService yhsxmxService) {
        this.yhsxmxService = yhsxmxService;
    }
    @Autowired
    public void setYhsxService(YhsxService yhsxService) {
        this.yhsxService = yhsxService;
    }
    @Autowired
    public void setKmdmDao(KmdmDao kmdmDao) {
        this.kmdmDao = kmdmDao;
    }
}
